//
//  LoginViewController.swift
//  issac-note
//
//  Created by Issac on 16/8/24.
//  Copyright © 2016年 Issac. All rights reserved.
//

import UIKit

import Alamofire
import SwiftyJSON


class LoginViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var username: UITextField!
    @IBOutlet var password: UITextField!
    @IBOutlet var loading: UIActivityIndicatorView!
    @IBOutlet var signIn: UIButton!
    @IBOutlet var signUp: UIButton!
    
    var segueToView: Bool = false
    var userMsg: NSDictionary?
    var requestStatus: Bool = false {
    
        didSet{
        
            if requestStatus {
            
                NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(segueToListView), userInfo: nil, repeats: false)
                requestStatus = false
            
            }else {
            
                self.loading.stopAnimating()
                self.alertTipAction("登录Issac-Note", message: "密码或账号有误", confirm: "确定")
            
            }
            
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        username.delegate = self
        password.delegate = self
        
        username.becomeFirstResponder()
        username.returnKeyType = UIReturnKeyType.Next
        username.tag = 1
        
        password.returnKeyType = UIReturnKeyType.Done
        password.tag = 2
        
        signIn.layer.cornerRadius = 5
        signUp.layer.cornerRadius = 5

    }

    override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
        
        return identifier == "toListView" ? false : true
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "toListView" {
        
            if let listView: ListTableViewController = segue.destinationViewController as? ListTableViewController {
                
                listView.uid = self.userMsg!["data"] as? String
                
            }
        
        }
    
    }
    
    //MARK: - IBAction
    @IBAction func loginAction(sender: UIButton) {
        
        self.loginCheckAction()
        
    }
    
    
    //MARK: - function-myself
    
    func segueToListView(){
    
        self.loading.stopAnimating()
        performSegueWithIdentifier("toListView", sender: nil)
    
    }
    
    //alert提示框
    func alertTipAction(title: String, message: String, confirm: String){
    
        let alertAction = UIAlertController(title: title, message: message, preferredStyle: .Alert)
         
        let cancelAction = UIAlertAction(title: confirm, style: .Cancel, handler: { sender in })
         
        alertAction.addAction(cancelAction)
        
        self.presentViewController(alertAction, animated: true, completion: nil)
        
    }
    
    //登录验证
    func loginCheckAction(){
    
        let username = self.username.text
        let password = self.password.text
        self.loading.startAnimating()
        
        if(
            username == "" ||
                password == ""
            ){
            
            self.loading.stopAnimating()
            self.alertTipAction("登录Issac-Note", message: "请输入完整信息", confirm: "确定")
            
        }else {
            
            loginCheckByServer(username, pwd: password)
            
        }
    
    }
    
    //MARK: - Delegate
    //return响应
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        if(textField.tag == 1){
        
            password.becomeFirstResponder()
        
        }else {
        
            self.loginCheckAction()
            
        }
        
        return true
        
        
    }
    
    
    //MARK: - GetDataFormServer
    func loginCheckByServer(user: String?, pwd: String?) {

        
        let url = "http://issac.website/issac-noteBackstage/Admin/index/login"
        let parameters = [
            "user" : user!,
            "pwd"  : pwd!
            ]
        
        
        Alamofire.request(.GET, url, parameters: parameters).validate().responseJSON { response in
            
            
            switch response.result {
            
            case .Success:
                
                if let value = response.result.value {
                
                    let json = JSON(value)
                    self.userMsg = json.dictionaryObject! as NSDictionary
                    self.requestStatus = json["status"] ? false : true
                    
                }
                
                
    
            case .Failure:
                
                print("fail")
                
                self.segueToView = false
            
            
            }
            
        }
        
        
    }
 

}
